package com.casic.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.casic.dao.IotDeviceDao;
import com.casic.dao.MongoDao;
import com.casic.dao.OEEMongoDao;
import com.casic.entity.IotData;
import com.casic.entity.IotOee;
import com.casic.entity.vo.CollectionPointVo;
import com.casic.entity.vo.DeviceStateStatisticsVo;
import com.casic.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xudezhi
 * @title: ApiController
 * @projectName iot-platform
 * @description: TODO
 * @date 2021/4/1513:40:39
 */
@Api(tags = "API接口")
@Slf4j
@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    MongoDao mongoDao;

    @Autowired
    OEEMongoDao oeeMongoDao;

    @Autowired
    IotDeviceDao iotDeviceDao;

    /**
     * 根据企业id获得运行数、待机数、故障数及设备总数（ 10  分钟以内）(mysql、mongo)
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据企业id获得运行数、待机数、故障数及设备总数（ 10  分钟以内）")
    @PostMapping(value="getEnterpriseRealTimeDataByOrgId.ht",produces="application/json; charset=UTF-8")
    public Map<String,Object> getEnterpriseRealTimeDataByOrgId(@ApiParam(value="参考示例：{\"orgId\":\"8090309\"} ") @RequestBody Map<String,String> params){
        String orgId="";
        if(params.containsKey("orgId")){
            orgId=params.get("orgId");
        }
        Map<String,Object> map = new HashMap<>();
        log.debug("getEnterpriseRealTimeDatas() invoked");
        //如果没有传入企业则查询全部的
//        if(orgId==null || "".equals(orgId)){
//            //未传入企业ID
//            map.put("code", R.RCode.PARAMETER_IS_INCORRECT.getCode());
//            map.put("msg", R.RCode.PARAMETER_IS_INCORRECT.getMsg());
//            return map;
//        }
        try {
            Map<String,Integer> dataMap = new HashMap<>();

            /**
             * 10分钟前的时间戳
             */
            String startTime = String.valueOf(new Date().getTime()-10*60*1000);
            /**
             * 当前时间戳
             */
            String endTime = String.valueOf(new Date().getTime());

            /**
             * 查询企业设备总数
             */
            Integer total= 0;
            if(orgId.equals("")){//所有的
                total=iotDeviceDao.getNum();
            }else{
                //指定企业的
               total=iotDeviceDao.getNumByOrgId(orgId);
            }


            dataMap.put("total", total);

//            /**
//             * 查询故障设备数(故障状态：3000)
//             */
//            List<DeviceStateStatisticsVo> gzs=mongoDao.findByOrgIdAndKAndVAndTBetween(orgId,"state","3000",startTime,endTime);
//            dataMap.put("gzs", gzs.size());
//            /**
//             * 查询待机设备数(状态：2000)
//             */
//            List<DeviceStateStatisticsVo> djs=mongoDao.findByOrgIdAndKAndVAndTBetween(orgId,"state","2000",startTime,endTime);
//            dataMap.put("djs", djs.size());
//            /**
//             * 查询运行设备数(状态：1000)
//             */
//            List<DeviceStateStatisticsVo> yxs=mongoDao.findByOrgIdAndKAndVAndTBetween(orgId,"state","1000",startTime,endTime);
//            dataMap.put("yxs", yxs.size());


            dataMap.put("gzs", 0);
            dataMap.put("djs", 0);
            dataMap.put("yxs", 0);

            List<DeviceStateStatisticsVo> voList=null;

            if(orgId.equals("")){//所有的
                voList= mongoDao.findByKAndTBetween("state",startTime,endTime);
            }else{
                //指定企业的
                voList= mongoDao.findByOrgIdAndKAndTBetween(orgId,"state",startTime,endTime);
            }

            List<String> gzList=new ArrayList<String>();
            List<String> djList=new ArrayList<String>();
            if(voList!=null&&voList.size()>0){
                //voList按3000/2000、1000倒序排列，设备状态优先级逐渐降低，所以上一个状态统计了，下一状态统计到了要排除掉
                for (DeviceStateStatisticsVo vo:voList) {
                    if(vo.getStatisticKey().equals("3000")){
                        //故障设备
                        dataMap.put("gzs", vo.getEquipments().size());
                        gzList=vo.getEquipments();
                    }
                    if(vo.getStatisticKey().equals("2000")){
                        //待机设备
                        djList=vo.getEquipments();
                        djList.removeAll(gzList);//排除待机统计进去的故障的设备
                        dataMap.put("djs", djList.size());
                    }
                    if(vo.getStatisticKey().equals("1000")){
                        //运行设备
                        List<String> list =vo.getEquipments();
                        list.removeAll(gzList);//排除待机统计进去的故障的设备
                        list.removeAll(djList);//排除统计进去的待机设备
                        dataMap.put("yxs", list.size());
                    }
                }
            }


            map.put("success", true);
            map.put("msg",dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("code", R.RCode.EXCEPTION_FOR_CODE.getCode());
            map.put("msg", R.RCode.EXCEPTION_FOR_CODE.getMsg());
        }
        return map;
    }


    /**
     * 查询企业设备总数（mysql）
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据企业id获得设备总数")
    @PostMapping(value="getCountDevicesByOrgId.ht",produces="application/json; charset=UTF-8")
    public Map<String,Object> getCountDevicesByOrgId(@ApiParam(value="参考示例：{\"orgId\":\"8090309\"}") @RequestBody Map<String,String> params){
        String orgId="";
        if(params.containsKey("orgId")){
            orgId=params.get("orgId");
        }
        Map<String,Object> map = new HashMap<>();
        if(orgId==null || "".equals(orgId)){
            //未传入企业ID
            map.put("code", R.RCode.PARAMETER_IS_INCORRECT.getCode());
            map.put("msg", R.RCode.PARAMETER_IS_INCORRECT.getMsg());
            return map;
        }
        /**
         * 查询企业设备总数
         */
        Integer total= iotDeviceDao.getNumByOrgId(orgId);
        map.put("success", true);
        map.put("data", total);

        return map;
    }

    /**
     * 根据设备  id  获得实时采集数据
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据设备  id  获得实时采集数据")
    @PostMapping(value="getDevDatasByDevIdPage.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getDevDatasByDevIdPage(@ApiParam(value="参考示例：{\"devId\":\"10000052281002\",\"currentPage\":2,\"pagesize\":1}") @RequestBody Map<String,String> params){
        Map<String,Object> map = new HashMap<>();
        try{
            String devId = "";
            if(params.containsKey("devId")){
                devId = params.get("devId");
            }

            int currentPage =  0;
            if(params.containsKey("currentPage")){
               currentPage=Integer.valueOf(params.get("currentPage"));
            }

            int pagesize = 20;
            if(params.containsKey("pagesize")){
                pagesize=Integer.valueOf(params.get("pagesize"));
            }

            if (devId == null || "".equals(devId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入设备唯一标识");
                return map;
            }

            List<IotData> list = new ArrayList<IotData>();
            //分页条件
            Pageable pageable = PageRequest.of(currentPage, pagesize, Sort.by(Sort.Direction.DESC, "t"));
            list=mongoDao.findByEquipment(devId,pageable);

            //---- 尝试调用另一种查询方法
//            /**
//             * 查询条件
//             */
//            Map queryMap=new HashMap();
//            queryMap.put("equipment",devId);
//
//            //此处是根据指定条件精确查询
//            ExampleMatcher matcher = ExampleMatcher
//                    .matching()
//                    .withMatcher("equipment", ExampleMatcher.GenericPropertyMatchers.contains());
//            Example<Map> example=Example.of(queryMap,matcher);
//            /**
//             * 调用查询
//             */
//            Page page=mongoDao.findAll(example,pageable);
//            list=page.getContent();

            map.put("success", true);
            map.put("data", list);

        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }

        return map;
    }


    /**
     * 根据设备  id  获得采集点列表
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = " 根据设备  id  获得采集点列表")
    @PostMapping(value="getCollectionByDevId.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getCollectionByDevId(@ApiParam(value="参考示例：{\"devId\":\"10000048428190\"} ")  @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();

        try{
            String devId = "";
            if(params.containsKey("devId")){
                devId = params.get("devId");
            }

            if (devId == null || "".equals(devId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入设备唯一标识");
                return map;
            }

            /**
             * 采集点列表
             */
            List<CollectionPointVo> data=new ArrayList();
            //查询采集点信息
            data=iotDeviceDao.findPointInfoById(devId);

            map.put("success", true);
            map.put("data", data);
            map.put("total",data==null?0:data.size());

        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }


        return map;
    }

    /**
     * 根据设备  id,colId  获得最新采集数据
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据设备  id,colId  获得最新采集数据")
    @PostMapping(value="getLastDatasByDevIdColId.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getLastDatasByDevIdColId(@ApiParam(value="参考示例：{\"devId\":\"10000050672740\",\"colId\":\"state\"} ") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();

        try{
            String devId = "";
            if(params.containsKey("devId")){
                devId = params.get("devId");
            }

            if (devId == null || "".equals(devId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入设备唯一标识");
                return map;
            }

            String colId = "";
            if(params.containsKey("colId")){
                colId = params.get("colId");
            }

            if (colId == null || "".equals(colId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入采集点");
                return map;
            }

            /**
             * 查询最新一条数据
             */
            IotData data=mongoDao.findFirstByEquipmentAndK(devId,colId,Sort.by(Sort.Direction.DESC,"t"));

            map.put("success", true);
            map.put("data", data);

        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }

        return map;
    }

    /**
     * 根据设备  id, colId, 时间范围获得采集数据
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据设备  id, colId, 时间范围获得采集数据")
    @PostMapping(value="getDatasByDevIdColIdTimes.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getDatasByDevIdColIdTimes(@ApiParam(value="参考示例：{\"devId\":\"10000052281002\",\"colId\":\"state\",\"startTime\":\"时间戳\",\"endTime\":\"时间戳\"} ") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();
        try{
            String devId = "";
            if(params.containsKey("devId")){
                devId = params.get("devId");
            }

            if (devId == null || "".equals(devId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入设备唯一标识");
                return map;
            }

            String colId = "";
            if(params.containsKey("colId")){
                colId = params.get("colId");
            }

            if (colId == null || "".equals(colId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入采集点");
                return map;
            }

            String startTime = String.valueOf("0");//起始时间1970-1-1 8:00
            if(params.containsKey("startTime")){
                startTime = params.get("startTime");
            }

            String endTime = String.valueOf(new Date().getTime());
            if(params.containsKey("endTime")){
                endTime = params.get("endTime");
            }

            /**
             * 查询数据
             */
            List<IotData> data=mongoDao.findByEquipmentAndKAndTBetween(devId,colId,startTime,endTime,Sort.by(Sort.Direction.DESC,"t"));

            map.put("success", true);
            map.put("data", data);

        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }
        return map;
    }

    /**
     * 根据设备  id,   colId, 时间范围获得采集数据（分页）
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据设备  id,   colId, 时间范围获得采集数据（分页）")
    @PostMapping(value="getDatasByDevIdColIdTimesPage.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getDatasByDevIdColIdTimesPage(@ApiParam(value="参考示例：{\"devId\":\"10000052281002\",\"colId\":\"state\",\"startTime\": " +
            "\"时间戳\",\"endTime\":\"时间戳\", " +
            "\"currentPage\":1,\"pagesize\":1} ") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();
        try{
            String devId = "";
            if(params.containsKey("devId")){
                devId = params.get("devId");
            }
            if (devId == null || "".equals(devId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入设备ID");
                return map;
            }

            String colId = "";
            if(params.containsKey("colId")){
                colId = params.get("colId");
            }

            if (colId == null || "".equals(colId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入采集点");
                return map;
            }

            String startTime = String.valueOf("0");//起始时间1970-1-1 8:00
            if(params.containsKey("startTime")){
                startTime = params.get("startTime");
            }

            String endTime = String.valueOf(new Date().getTime());
            if(params.containsKey("endTime")){
                endTime = params.get("endTime");
            }

            int currentPage =  0;
            if(params.containsKey("currentPage")){
                currentPage=Integer.valueOf(params.get("currentPage"));
            }

            int pagesize = 20;
            if(params.containsKey("pagesize")){
                pagesize=Integer.valueOf(params.get("pagesize"));
            }

            //分页条件
            Pageable pageable = PageRequest.of(currentPage, pagesize, Sort.by(Sort.Direction.DESC, "t"));


            /**
             * 查询数据
             */
            Page<IotData> data=mongoDao.findByEquipmentAndKAndTBetween(devId,colId,startTime,endTime,pageable);


            map.put("success", true);
            map.put("data", data.getContent());
            map.put("totalCount",data.getTotalElements());

        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }
        return map;
    }


    /**
     * 根据时间图表获取信息（整体逻辑修改，时间大于等于 1  一天，则每隔  30  分钟返回一条数据， hbase ）
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据时间图表获取信息（整体逻辑修改，时间大于等" +
            " 于 1  一天，则每隔  30  分钟返回一条数据， hbase ） ")
    @PostMapping(value="getHstoricalDateForChart.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getHstoricalDateForChart(@ApiParam(value="参考示例：{ \"devId\":\"10000056110030\", \"colId\":\"state\"," +
            "            \"startTime\":\"时间戳\"," +
            "            \"endTime\":\"时间戳\",\"sort\":\"desc\" }") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();
        try{
            String devId = "";
            if(params.containsKey("devId")){
                devId = params.get("devId");
            }

            if (devId == null || "".equals(devId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入设备唯一标识");
                return map;
            }

            String colId = "";
            if(params.containsKey("colId")){
                colId = params.get("colId");
            }

            if (colId == null || "".equals(colId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入采集点");
                return map;
            }

            Sort.Direction direction= Sort.Direction.ASC;
            if(params.containsKey("sort")){
                String sort = params.get("sort");
                if("desc".equals(sort)){
                    direction=Sort.Direction.DESC;
                }else{
                    direction=Sort.Direction.ASC;
                }
            }

            String startTime = String.valueOf("0");//起始时间1970-1-1 8:00
            if(params.containsKey("startTime")){
                startTime = params.get("startTime");
            }

            String endTime = String.valueOf(new Date().getTime());
            if(params.containsKey("endTime")){
                endTime = params.get("endTime");
            }

            List<IotData> data= new ArrayList<>();
            if (Long.valueOf(endTime) - Long.valueOf(startTime) >= 24 * 3600000) {//超过24小时

                //全查
                data=mongoDao.findByEquipmentAndKAndTBetween(devId,colId,startTime,endTime,Sort.by(direction,"t"));

                Long spacetime = 1800 * 1000L;
                int i = 1000; //使之不进入循环查询，因为太慢了
                Long et=Long.valueOf(endTime);
                Long st=Long.valueOf(startTime);
                while (i < 48*7 && et > Long.valueOf(startTime)) {
                    //正序需要从st开始
                    if(direction==Sort.Direction.ASC){
                        st+=spacetime;//累加半个小时
                        et=st+spacetime;//结束时间等于开始时间加半个小时
                    }else{
                        if(i!=0){
                            et-=spacetime;//累减半个小时
                        }
                        st=et-spacetime;//开始时间是半个小时差距
                    }
                    //查询半个小时内的第一条
                    IotData d=mongoDao.findFirstByEquipmentAndKAndTBetween(devId,colId,String.valueOf(st),String.valueOf(et),Sort.by(direction,"t"));
                    if(d!=null){
                        data.add(d);//放入到集合
                    }
                    i++;
                }
            } else {
                /**
                 * 查询数据
                 */
                data=mongoDao.findByEquipmentAndKAndTBetween(devId,colId,startTime,endTime,Sort.by(direction,"t"));
            }

            map.put("success", true);
            map.put("data", data);
            map.put("records",data.size());

        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }

        return map;
    }


    /**
     * 根据设备  id  获得最新状态数据(30分钟内的数据，空是离线)
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据设备  id  获得最新状态数据(30分钟内的数据，空是离线)")
    @PostMapping(value = "getStatusByDevId.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getStatusByDevId(@ApiParam(value="参考示例：{\"devId\":\"10000050672740\"}") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();
        try{
            String devId = "";
            if(params.containsKey("devId")){
                devId = params.get("devId");
            }

            if (devId == null || "".equals(devId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入设备唯一标识");
                return map;
            }

            String colId = "state";


            String endTime = String.valueOf(new Date().getTime());
            String startTime = String.valueOf(new Date().getTime()-(1800 * 1000L));//半个小时内的数据
            //查询半个小时内的第一条
            IotData data=mongoDao.findFirstByEquipmentAndKAndTBetween(devId,colId,startTime,endTime,Sort.by(Sort.Direction.DESC,"t"));

            map.put("success", true);
            map.put("data", data);

        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }
        return map;
    }

// 调研发现此接口所调用的地址不用，所以不开发了
//    @ApiOperation(value = "从  Hbase  设备表  devId  中返回最新一条  state （ 30  分钟以内）")
//    @PostMapping(value="getWhHsRateByDevId.ht",produces="application/json; charset=UTF-8")
//    public Map<String, Object> getWhHsRateByDevId(@ApiParam(value="参考示例：{\"devId\":\"10000050672740\"}") @RequestBody Map<String,String> params){
//        Map<String, Object> map=new HashMap<>();
//
//        return map;
//    }


    /**
     * 根据企业  id,key  获得运行数  or  故障数  or  待机数 （ 24小时以内  mongo ）
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据企业  id,key  获得运行数  or  故障数  or  待机数 （ 24" +
            " 小时以内  mongo ）")
    @PostMapping(value="getEnterpriseRealTimeDataByOrgIdAndKey.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getEnterpriseRealTimeDataByOrgIdAndKey(@ApiParam(value="参考示例：{\"orgId\":\"740114\",\"key\":\"yxs\",\"currentPage\":\"0\",\"pageSize\":\"20\",\"sort\":1}") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();

        try {

            String orgId="";
            if(params.containsKey("orgId")){
                orgId=params.get("orgId");
            }
            String key="";
            if(params.containsKey("key")){
                key=params.get("key");
            }

            if(orgId==null || "".equals(orgId)){
                //未传入企业ID
                map.put("code", R.RCode.PARAMETER_IS_INCORRECT.getCode());
                map.put("msg", R.RCode.PARAMETER_IS_INCORRECT.getMsg());
                return map;
            }

            if(!"djs".equals(key)&&!"yxs".equals(key)&&!"gzs".equals(key)){
                //key不正确(关键字错误，不是待机数、运行数、故障数)
                map.put("code", R.RCode.PARAMETER_IS_INCORRECT.getCode());
                map.put("msg", R.RCode.PARAMETER_IS_INCORRECT.getMsg());
                return map;
            }

            int currentPage =  0;
            if(params.containsKey("currentPage")){
                currentPage=Integer.valueOf(params.get("currentPage"));
            }

            int pageSize = 20;
            if(params.containsKey("pageSize")){
                pageSize=Integer.valueOf(params.get("pageSize"));
            }
            //排序
            int sort = 1;
            if(params.containsKey("sort")){
                sort=Integer.valueOf(params.get("sort"));
            }

//            Map<String,Integer> dataMap = new HashMap<>();
            List<Map<String,String>> lists=new ArrayList<Map<String,String>>();
            /**
             * 24小时前的时间戳
             */
            String startTime = String.valueOf(new Date().getTime()-24*60*60*1000);
            /**
             * 当前时间戳
             */
            String endTime = String.valueOf(new Date().getTime());
            Long nowTime=Long.valueOf(endTime);
            Long agoTime=Long.valueOf(startTime);

            Long et=Long.valueOf(endTime);
            Long st=Long.valueOf(startTime);

            Long spacetime = 300 * 1000L; //五分钟
            int i=currentPage*pageSize;//起始条数
            while (i < 288 && i<(currentPage+1)*pageSize && et > Long.valueOf(startTime) && st<Long.valueOf(endTime)) {
                if(sort==1){
                    et=nowTime-(spacetime*i);//累减5分钟
                    st=nowTime-(spacetime*i)-spacetime;//开始时间是5分钟前
                }else{
                    et=agoTime+(spacetime*i)+spacetime;//累加5分钟
                    st=agoTime+(spacetime*i);//开始时间是5分钟前
                }
                Date d=new Date();
                d.setTime(et);

                //先设置默认值
                Map<String,String> rmap = new HashMap<>();
                rmap.put("k", key);
                rmap.put("v","0");
                rmap.put("t", String.valueOf(et));
                rmap.put("time", DateUtil.format(d,"yyyy-MM-dd HH:mm:ss"));

                List<DeviceStateStatisticsVo> voList=mongoDao.findByOrgIdAndKAndTBetween(orgId,"state",String.valueOf(st),String.valueOf(et));
                List<String> gzList=new ArrayList<String>();
                List<String> djList=new ArrayList<String>();
                if(voList!=null&&voList.size()>0){
                    //voList按3000/2000、1000倒序排列，设备状态优先级逐渐降低，所以上一个状态统计了，下一状态统计到了要排除掉
                    for (DeviceStateStatisticsVo vo:voList) {
                        if(vo.getStatisticKey().equals("3000")){
                            //故障设备
//                            dataMap.put("gzs", vo.getEquipments().size());
                            if("gzs".equals(key)){
                                rmap.put("v", String.valueOf(vo.getEquipments().size()));
                                lists.add(rmap);
                            }
                            gzList=vo.getEquipments();
                        }
                        if(vo.getStatisticKey().equals("2000")){
                            //待机设备
                            djList=vo.getEquipments();
                            djList.removeAll(gzList);//排除待机统计进去的故障的设备
//                            dataMap.put("djs", djList.size());
                            if("djs".equals(key)){
                                rmap.put("v", String.valueOf(djList.size()));
                                lists.add(rmap);
                            }
                        }
                        if(vo.getStatisticKey().equals("1000")){
                            //运行设备
                            List<String> list =vo.getEquipments();
                            list.removeAll(gzList);//排除待机统计进去的故障的设备
                            list.removeAll(djList);//排除统计进去的待机设备
//                            dataMap.put("yxs", list.size());
                            if("yxs".equals(key)){
                                rmap.put("v", String.valueOf(list.size()));
                                lists.add(rmap);
                            }
                        }
                    }
                }else{
                    rmap.put("v", "0");
                    lists.add(rmap);
                }

                i++;
            }

            map.put("success", true);
            map.put("msg",lists);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("code", R.RCode.EXCEPTION_FOR_CODE.getCode());
            map.put("msg", R.RCode.EXCEPTION_FOR_CODE.getMsg());
        }


        return map;
    }

    /**
     * 根据企业id 和设备ID 日期范围获得效率列表 （24小时内 mongo ）
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据企业id 和设备ID 日期范围获得效率列表 （24小时内 mongo ）")
    @PostMapping(value="getMesDeviceOeebyDateSt.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getMesDeviceOeebyDateSt(@ApiParam(value="参考示例：{\"orgId\":\"530000\",\"devId\":\"1233\",\"startTime\":\"时间戳\",\"endTime\":\"时间戳\"}") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();
        try{

            /**
             * 企业ID没啥用，因为设备ID就确定了唯一设备
             */
//            String orgId="";
//            if(params.containsKey("orgId")){
//                orgId=params.get("orgId");
//            }
//            if(orgId==null || "".equals(orgId)){
//                //未传入企业ID
//                map.put("code", R.RCode.PARAMETER_IS_INCORRECT.getCode());
//                map.put("msg", R.RCode.PARAMETER_IS_INCORRECT.getMsg());
//                return map;
//            }

            String devId="";
            if(params.containsKey("devId")){
                devId=params.get("devId");
            }
            if(devId==null || "".equals(devId)){
                //未传入设备ID
                map.put("code", R.RCode.PARAMETER_IS_INCORRECT.getCode());
                map.put("msg", R.RCode.PARAMETER_IS_INCORRECT.getMsg());
                return map;
            }

            //为了附和原有的接口格式
            Map<String, Object> resultMap = new HashMap<String, Object>();
            List list=new ArrayList();


            //获取日期为昨天
            DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar=Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY,-24);
            String yesterdayDate=dateFormat.format(calendar.getTime());
            /**
             * 查询有没有已经统计好的数据
             */
            IotOee data=oeeMongoDao.findByEquipmentAndDate(devId,yesterdayDate);

            /**
             * 判断数据存在性
             */
            if(data!=null){
                list.add(data);
            }else{
                /**
                 * 从数据信息库查询
                 */
                searchOee(map, devId, resultMap, list);
            }

            resultMap.put("list", list);
            map.put("success", true);
            map.put("data", resultMap);
            map.put("totalCounts", 1);
            map.put("totalPages", 1);
            map.put("currentPage", 1);
            map.put("pageSize", 1);
        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }
        return map;
    }

    /**
     * 沙勋设备OEE信息
     * @param map
     * @param devId
     * @param resultMap
     * @param list
     */
    private void searchOee(Map<String, Object> map, String devId, Map<String, Object> resultMap, List list) {
        /**
         * 昨天0点时间戳
         */
        Calendar startTime = Calendar.getInstance();
        startTime.set(startTime.get(Calendar.YEAR),startTime.get(Calendar.MONTH),startTime.get(Calendar.DAY_OF_MONTH)-1,0,0,0);
        long st = startTime.getTime().getTime();
        /**
         * 昨天23:59:59时间戳
         */
        Calendar endTime = Calendar.getInstance();
        endTime.set(endTime.get(Calendar.YEAR),endTime.get(Calendar.MONTH),endTime.get(Calendar.DAY_OF_MONTH)-1,23,59,59);
        long et = endTime.getTime().getTime();

        /**
         * 设置三种情况出现的次数
         */
        int yxs=0;
        int djs=0;
        int gzs=0;

        Long spacetime = 5* 60 * 1000L; //五分钟
        int i=0;//起始条数
        Long stTemp=st;//起始时间
        Long etTemp=st+spacetime;//起始结束时间
        /**
         * 获取分别的个数
         */
        while (i < 288 && etTemp < Long.valueOf(et)) {
            stTemp+=spacetime;//起始时间
            etTemp+=spacetime;//起始结束时间

            /**
             * 查询5分钟内的一条状态采集数据
             */
            IotData data=mongoDao.findFirstByEquipmentAndKAndTBetween(devId,"state",String.valueOf(stTemp),String.valueOf(etTemp),Sort.by(Sort.Direction.DESC,"t"));
            if(data!=null){
                gzs+= "3000".equals(data.getV())?1:0;
                djs+= "2000".equals(data.getV())?1:0;
                yxs+= "1000".equals(data.getV())?1:0;
            }
            i++;
        }

        Double allTime=86400d;//24小时的秒数
        /**
         * 时长计算
         */
        Double yxsc=yxs*300d;//运行秒数
        Double gzsc=gzs*300d;//故障秒数
        Double djsc=djs*300d;//待机秒数
        Double kjsc=NumberUtil.add(yxsc,gzsc,djsc).doubleValue();//开机总时长
        Double gjsc=NumberUtil.sub(allTime,kjsc);//关机时长
        /**
         * 效率计算
         */
        Double yxl= NumberUtil.div(yxsc,allTime) ;//运行率
        Double gzl=NumberUtil.div(gzsc,allTime);//故障率
        Double djl=NumberUtil.div(djsc,allTime);//待机率
        Double kjl=NumberUtil.div(kjsc,allTime);//开机率
        Double oee=kjsc==0?0d:NumberUtil.div(yxsc,kjsc); //设备oee
        Double oksc=NumberUtil.add(yxsc,djsc);//运行加待机，可用状态
        Double lyl=kjsc==0?0d:NumberUtil.div(oksc,allTime);//利用率

        IotOee iotoee=new IotOee();
        iotoee.setEquipment(devId);
        iotoee.setDate(DateUtil.format(endTime.getTime(),"yyyy-MM-dd"));
        iotoee.setYxsc(yxsc);
        iotoee.setGzsc(gzsc);
        iotoee.setDjsc(djsc);
        iotoee.setYxl(yxl);
        iotoee.setGzl(gzl);
        iotoee.setDjl(djl);
        iotoee.setKjl(kjl);
        iotoee.setOee(oee);
        iotoee.setLyl(lyl);
        iotoee.setKjsc(kjsc);
        iotoee.setGjsc(gjsc);
        oeeMongoDao.save(iotoee);

        list.add(iotoee);
    }

    /**
     * 根据  orgId  找到该企业的设备在各个省的分布，降序排列
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据  orgId  找到该企业的设备在各个省的分布，降序排列")
    @PostMapping(value="getProvinceAndDevs.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getProvinceAndDevs(@ApiParam(value="参考示例：{\"orgId\":\"8090309\"}") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();
        try{
            String orgId=null;
            if(params.containsKey("orgId")){
                orgId=params.get("orgId");
            }
            //可以不传，查询所有的企业
//            if(orgId==null || "".equals(orgId)){
//                //未传入企业ID
//                map.put("code", R.RCode.PARAMETER_IS_INCORRECT.getCode());
//                map.put("msg", R.RCode.PARAMETER_IS_INCORRECT.getMsg());
//                return map;
//            }
            /**
             * 查询企业设备总数
             */
            List<Map<String, String>> proviceNums= iotDeviceDao.getProvinceNumByOrgId(orgId);

            map.put("success", true);
            map.put("data", proviceNums);
        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }
        return map;
    }

//    @CrossOrigin //所有接口允许跨域调用
//    @ApiOperation(value = "根据制造商获得前  10  活跃设备企业")
//    @PostMapping(value="getActiveEnterprisebymatOrgId.ht",produces="application/json; charset=UTF-8")
//    public Map<String, Object> getActiveEnterprisebymatOrgId(@ApiParam(value="参考示例：{\"orgId\":\"8294075\"} ") @RequestBody Map<String,String> params){
//        Map<String, Object> map=new HashMap<>();
//
//        return map;
//    }

//    @CrossOrigin //所有接口允许跨域调用
//    @ApiOperation(value = "获得所有设备活跃度")
//    @PostMapping(value="getActiveEquipmentbyOrgId.ht",produces="application/json; charset=UTF-8")
//    public Map<String, Object> getActiveEquipmentbyOrgId(@ApiParam(value="参考示例：{\"orgId\":\"8294075\"} ") @RequestBody Map<String,String> params){
//        Map<String, Object> map=new HashMap<>();
//
//        return map;
//    }

    /**
     * 根据企业查询所有设备
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据企业查询所有设备")
    @PostMapping(value="getDevicesByOrgId.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getDevicesByOrgId(@ApiParam(value="参考示例：{\"orgId\":\"8294075\"} ") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();

        try{
            String orgId = "";
            if(params.containsKey("orgId")){
                orgId = params.get("orgId");
            }

            if (orgId == null || "".equals(orgId.trim())) {
                map.put("success", false);
                map.put("errorCode", "500");
                map.put("error", "请传入企业唯一标识");
                return map;
            }


            List<Map<String, String>> data=iotDeviceDao.findListByOrgId(orgId);
            map.put("success", true);
            map.put("data", data);

        }catch (Exception e){
            log.info(e.getMessage());
            map.put("code", R.RCode.PARAMETER_VALID_FALIURE.getCode());
            map.put("msg", R.RCode.PARAMETER_VALID_FALIURE.getMsg());
            return map;
        }


        return map;
    }

//    @CrossOrigin //所有接口允许跨域调用
//    @ApiOperation(value = "根据企业id获得各设备的状态，已停用")
//    @PostMapping(value="getAllDevsStateByOrgId.ht",produces="application/json; charset=UTF-8")
//    public Map<String, Object> getAllDevsStateByOrgId(@RequestBody Map<String,String> params){
//        Map<String, Object> map=new HashMap<>();
//
//        return map;
//    }


//    @CrossOrigin //所有接口允许跨域调用
//    @ApiOperation(value = "getMesDeviceOeeMessageSt")
//    @PostMapping(value="getMesDeviceOeeMessageSt.ht",produces="application/json; charset=UTF-8")
//    public Map<String, Object> getMesDeviceOeeMessageSt(@RequestBody Map<String,String> params){
//        Map<String, Object> map=new HashMap<>();
//
//        return map;
//    }


//    @CrossOrigin //所有接口允许跨域调用
//    @ApiOperation(value = "getEnterpriseRealTimeDataByMatOrgIdAndKeyHzsk")
//    @PostMapping(value="getEnterpriseRealTimeDataByMatOrgIdAndKeyHzsk",produces="application/json; charset=UTF-8")
//    public Map<String, Object> getEnterpriseRealTimeDataByMatOrgIdAndKeyHzsk(@RequestBody Map<String,String> params){
//        Map<String, Object> map=new HashMap<>();
//
//        return map;
//    }

//    @CrossOrigin //所有接口允许跨域调用
//    @ApiOperation(value = "getJgjsByDevId")
//    @PostMapping(value="getJgjsByDevId",produces="application/json; charset=UTF-8")
//    public Map<String, Object> getJgjsByDevId(@RequestBody Map<String,String> params){
//        Map<String, Object> map=new HashMap<>();
//
//        return map;
//    }


    /**
     * 获取运行统计
     * @param params
     * @return
     */
    @CrossOrigin //所有接口允许跨域调用
    @ApiOperation(value = "根据企业  id（可选）,获得运行数 故障数 待机数 （ 24" +
            " 小时以内  mongo ）")
    @PostMapping(value="getOperationStatistics.ht",produces="application/json; charset=UTF-8")
    public Map<String, Object> getOperationStatistics(@ApiParam(value="参考示例：{\"orgId\":\"740114\",\"sort\":1}") @RequestBody Map<String,String> params){
        Map<String, Object> map=new HashMap<>();

        try {

            String orgId="";
            if(params.containsKey("orgId")){
                orgId=params.get("orgId");
            }


            //排序
            int sort = 1;
            if(params.containsKey("sort")){
                sort=Integer.valueOf(params.get("sort"));
            }

//            Map<String,Integer> dataMap = new HashMap<>();
            List<Map<String,String>> lists=new ArrayList<Map<String,String>>();

            /**
             * 获取上一个整点或者半点
             */
            Calendar ca = Calendar.getInstance();
            ca.setTime(new Date());
            if(ca.get(Calendar.MINUTE)<30){
                ca.set(Calendar.MINUTE, 0);
            }else{
                ca.set(Calendar.MINUTE, 30);
            }
            ca.set(Calendar.SECOND, 0);

            /**
             * 24小时前的时间戳
             */
            String startTime = String.valueOf(ca.getTime().getTime()-24*60*60*1000);
            /**
             * 当前时间戳
             */
            String endTime = String.valueOf(ca.getTime().getTime());
            Long nowTime=Long.valueOf(endTime);
            Long agoTime=Long.valueOf(startTime);

            Long et=Long.valueOf(endTime);
            Long st=Long.valueOf(startTime);

            Long spacetime = 1800 * 1000L; //三十分钟
            int i=0;//起始条数


            while (i < 48 && et > Long.valueOf(startTime) && st<Long.valueOf(endTime)) {
                if(sort==1){
                    et=nowTime-(spacetime*i);//累减间隔时间
                    st=nowTime-(spacetime*i)-spacetime;//开始时间是间隔时间
                }else{
                    et=agoTime+(spacetime*i)+spacetime;//累加间隔时间
                    st=agoTime+(spacetime*i);//开始时间是间隔时间
                }
//                Date d=new Date();
//                d.setTime(et);

                List<DeviceStateStatisticsVo> voList=null;
                if(!"".equals(orgId)) {
                    voList=mongoDao.findByOrgIdAndKAndTBetween(orgId,"state",String.valueOf(st),String.valueOf(et));
                }else {
                    voList=mongoDao.findByKAndTBetween("state",String.valueOf(st),String.valueOf(et));
                }

                /**
                 * 设置当前时刻默认值
                 */
                Map<String,String> rmap = new HashMap<>();
                rmap.put("t", String.valueOf(et));
                rmap.put("time", DateUtil.format(new Date(st),"MM月dd日HH:mm")+"-"+ DateUtil.format(new Date(et),"HH:mm"));
                rmap.put("gzs","0");//默认值
                rmap.put("djs","0");//默认值
                rmap.put("yxs","0");//默认值

                List<String> gzList=new ArrayList<String>();
                List<String> djList=new ArrayList<String>();
                if(voList!=null&&voList.size()>0){
                    //voList按3000/2000、1000倒序排列，设备状态优先级逐渐降低，所以上一个状态统计了，下一状态统计到了要排除掉
                    for (DeviceStateStatisticsVo vo:voList) {
                        if(vo.getStatisticKey().equals("3000")){
                            //故障设备
                            rmap.put("gzs", String.valueOf(vo.getEquipments().size()));
                            gzList=vo.getEquipments();
                        }
                        if(vo.getStatisticKey().equals("2000")){
                            //待机设备
                            djList=vo.getEquipments();
                            djList.removeAll(gzList);//排除待机统计进去的故障的设备
                            rmap.put("djs", String.valueOf(djList.size()));
                        }
                        if(vo.getStatisticKey().equals("1000")){
                            //运行设备
                            List<String> list =vo.getEquipments();
                            list.removeAll(gzList);//排除待机统计进去的故障的设备
                            list.removeAll(djList);//排除统计进去的待机设备
                            rmap.put("yxs", String.valueOf(list.size()));
                        }

                    }
                }else{
                    rmap.put("yxs", "0");
                    rmap.put("djs", "0");
                    rmap.put("gzs", "0");
                }
                lists.add(rmap);

                i++;
            }

            map.put("success", true);
            map.put("msg",lists);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("code", R.RCode.EXCEPTION_FOR_CODE.getCode());
            map.put("msg", R.RCode.EXCEPTION_FOR_CODE.getMsg());
        }


        return map;
    }

}
